<?php

namespace App\Jobs;

use App\Service\users\AccountRecordService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

/**
 * 金额记录队列
 */
class AccountChangeQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $timeout = 60;

    protected array $retry_map = [
        '1' => 10,
        '2' => 30,
        '3' => 120
    ];

    private array $data;

    /**
     * Create a new job instance.
     */
    public function __construct($data)
    {
        $this->data = $data;
        $this->data['operator'] = $this->data['operator'] ?? 'user';
        Log::info(Carbon::now()->toDateTimeString() . ' 金额记录开始');
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        try {
            AccountRecordService::instance()->createAmountRecord(
                $this->data['uid'],
                $this->data['num'],
                $this->data['credit_type'],
                $this->data['type'],
                $this->data['table_id'],
                $this->data['remark'],
                $this->data['operator']
            );
        } catch (\Throwable $e) {
            Log::error(Carbon::now()->toDateTimeString() . ' 金额记录失败：' . $e->getMessage() . $e->getLine() . $e->getFile());
            $this->release($this->retry_map[$this->attempts()]);
        }
    }
}
